package com.doit.mr.day07.join;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @DATE 2021/12/9/14:40
 * @Author MDK
 * @Version 2021.2.2
 **/
public class Join {
    static  class JoinMapper extends Mapper<LongWritable, Text, Text, NullWritable>{
        Map<String, String> mp = new HashMap<>();
        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            //使用本地流读取用户数据 将用户数据存储在Map集合中
            BufferedReader br = new BufferedReader(new FileReader("user.txt"));
            String line = null;
            while ((line = br.readLine())!= null){
                String uid = line.split(",")[0];
                mp.put(uid, line);
            }
        }

        //只加载订单数据
        Text k = new Text();
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String uid = line.split("\\s+")[1];
            //根据UID输出用户信息  order012 u001
            String user = mp.get(uid);
            String res = user + "," + line;
            k.set(res);
            //输出数据
            context.write(k, NullWritable.get());
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.set("mapreduce.framework.name","yarn");
        Job job = Job.getInstance(conf, "mpside _join");
        //设置user数据为缓存数据,数据就会缓存在所有运行MT机器的类路径下
        job.addCacheFile(new URI("hdfs://linux01:8020/data/user.txt"));
        job.setJarByClass(Join.class);
        job.setMapperClass(JoinMapper.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
        //输入路径的时候  指定文件夹下不能有用户信息,只有订单信息
        FileInputFormat.setInputPaths(job, new Path("/data/join/"));
        FileOutputFormat.setOutputPath(job, new Path("/data/join_res"));
        job.waitForCompletion(true);
    }
}
